package com.fortune.app.utils;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;

import com.fortune.app.FortuneApplication;
import com.fortune.app.models.ZodiacFortune;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.Map;

/**
 * 每日提醒广播接收器，用于处理每日运势提醒
 */
public class DailyReminderReceiver extends BroadcastReceiver {
    private static final String TAG = "DailyReminderReceiver";
    
    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(TAG, "Daily reminder received");
        
        // 检查用户是否设置了个人信息
        FortuneApplication app = (FortuneApplication) context.getApplicationContext();
        if (!app.isUserInfoSet()) {
            Log.d(TAG, "User info not set, skipping daily reminder");
            return;
        }
        
        // 获取用户生日
        String birthDate = app.getUserBirthDate();
        
        // 获取当前日期
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.CHINA);
        String currentDate = dateFormat.format(new Date());
        
        // 生成今日运势
        ZodiacFortune zodiacFortune = new ZodiacFortune();
        Map<String, Object> result = zodiacFortune.generateDailyHoroscope(birthDate, currentDate);
        
        if (result.isEmpty()) {
            Log.e(TAG, "Failed to generate daily horoscope");
            return;
        }
        
        // 获取星座信息
        @SuppressWarnings("unchecked")
        Map<String, Object> zodiacInfo = (Map<String, Object>) result.get("zodiac_sign");
        String zodiacName = (String) zodiacInfo.get("name");
        
        // 获取运势评分
        @SuppressWarnings("unchecked")
        Map<String, Integer> scores = (Map<String, Integer>) result.get("scores");
        int overallScore = scores.get("overall");
        
        // 获取幸运信息
        @SuppressWarnings("unchecked")
        Map<String, Object> luckyInfo = (Map<String, Object>) result.get("lucky_info");
        String luckyDirection = (String) luckyInfo.get("direction");
        
        // 构建通知标题和内容
        String title = "今日运势提醒";
        String message = String.format("%s今日运势%s颗星，吉方位：%s", 
                zodiacName, getStars(overallScore), luckyDirection);
        
        // 发送通知
        NotificationHelper.sendDailyFortuneNotification(context, title, message);
        
        // 重新设置明天的提醒
        NotificationHelper.scheduleDailyReminder(context);
    }
    
    /**
     * 根据评分获取星星表示
     */
    private String getStars(int score) {
        StringBuilder stars = new StringBuilder();
        for (int i = 0; i < score; i++) {
            stars.append("★");
        }
        for (int i = score; i < 5; i++) {
            stars.append("☆");
        }
        return stars.toString();
    }
}
